package aaa.screen;

import greendroid.app.GDActivity;
import greendroid.graphics.drawable.ActionBarDrawable;
import greendroid.widget.ActionBarItem;
import greendroid.widget.ActionBarItem.Type;
import greendroid.widget.LoaderActionBarItem;
import greendroid.widget.NormalActionBarItem;
import aaa.database.Database;
import aaa.exception.AAAException;
import aaa.main.R;
import aaa.schedule.Schedule;
import aaa.schedule.ScheduleConstants;
import aaa.schedule.ScheduleListAdapter;
import aaa.schedule.UpdateListener;
import aaa.update.UpdateManager;
import aaa.update.UpdateNotifier;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class WelcomeScreen extends GDActivity implements UpdateListener, ScheduleConstants {
	
	private static final int REFRESH = 0 ;

	private ListView liste;
	private ScheduleListAdapter adapter ;
	private String nameCurrentSchedule;
	protected Database db ;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("aaa" ,"UI running in thread : "+Thread.currentThread()) ;
//		if (UpdateManager.getInstance() == null) {
//			UpdateManager.resume() ;
//		}// if
//		UpdateManager.getInstance().addListener(this) ;
		this.setTitle("Emploi du temps");
		this.setActionBarContentView(R.layout.w_screen);
		this.initActionBar();
		this.initializeAddSchedule() ;
	}// onCreate(Bundle)

	public void initActionBar() {
		this.addActionBarItem(Type.Refresh, REFRESH);
		this.addActionBarItem(getActionBar()
				.newActionBarItem(NormalActionBarItem.class)
				.setDrawable(new ActionBarDrawable(this, R.drawable.ic_action_bar_info)), R.id.action_bar_view_info);
	}

	@Override
	protected void onStart() {
		super.onStart();
		UpdateNotifier.addListener(this) ;
		this.createScheduleList() ;
		this.onUpdate() ;
	}
	
	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
		switch (item.getItemId()) {
		case REFRESH:
			if (this.adapter.getCount() == 0) {
				LoaderActionBarItem refreshItem = (LoaderActionBarItem) item ;
				refreshItem.setLoading(false) ;
			} else {
				this.updateAllSchedules() ;
			}
			break;

		case R.id.action_bar_view_info:
//			//TODO
//			Toast.makeText(this, "Fin du trace.", Toast.LENGTH_SHORT).show() ;
//			Debug.stopAllocCounting() ;
			this.startActivity(new Intent(this, InfoTabActivity.class));
			return true ;

		default:
			return super.onHandleActionBarItemClick(item, position);
			
		}
		return true ;
	}
	
	@Override
	protected void onStop() {
		UpdateNotifier.removeListener(this) ;
		this.adapter.clear() ;
		super.onStop();
	}

	/**
	 * Retrieves the names of the schedules and displays them
	 * on the screen.
	 */
	protected void createScheduleList() {
		this.db = new Database(this) ; 
//		for(int schedule=0; schedule<10; ++schedule) {
//			try {
//				this.db.insertSchedule(new Schedule(1, "sch"+schedule, "21992,21993", 15, "null", 1, "2012/02/07 23:15")) ;
//			} catch (Exception e) {}
//		}
		if (this.liste == null) {
			this.liste = (ListView) this.findViewById(R.id.listeEdt) ; 
			this.liste.setEmptyView(findViewById(R.id.empty)); 
			this.adapter = new ScheduleListAdapter(this, this.db, this.db.getSchedulesName()) ;
			this.liste.setAdapter(this.adapter) ;
			registerForContextMenu(liste);  

			this.liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> a, View v, int position, long id) {
					Intent intent = new Intent(WelcomeScreen.this, ScheduleScreen.class) ;
					nameCurrentSchedule = adapter.getItem(position);
					intent.putExtra("aaa.screen.nameCurrentSchedule", nameCurrentSchedule);
					WelcomeScreen.this.startActivity(intent) ;
				}
			}) ;                          
		} else {
			this.adapter.setSchedules(this.db.getSchedulesName()) ;
		}// if

	}// createScheduleList()

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
		this.nameCurrentSchedule = adapter.getItem(info.position);
		Database db = new Database(this) ;
		int status = db.getScheduleStatus(this.nameCurrentSchedule) ;
//		if (UpdateManager.getInstance().getScheduleStatus(nameCurrentSchedule) == STATUS_UPDATING)
		if (status == STATUS_UPDATING) {
			return ;
		}// if
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.context_menu_schedule, menu);
		menu.setHeaderTitle(this.nameCurrentSchedule);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.modify:
			Intent intent = new Intent(WelcomeScreen.this, EditScheduleScreen.class) ;
			//Permet de passer le nom de l'emploi du temps à l'activité EditScheduleScreen
			intent.putExtra("aaa.screen.nameCurrentSchedule", nameCurrentSchedule);
			this.startActivity(intent) ;
			return true;
		case R.id.delete:
			this.deleteSchedule();
			return true;
		case R.id.info:
			this.detailsDisplay();
			return true;

		default:
			return super.onContextItemSelected(item);
		}
	}

	/**      
	 * Initializes the "add schedule" functionality.
	 *
	 * <p>Add a listener to the "add" button.
	 */
	private void initializeAddSchedule () {
		final Button button = (Button) findViewById(R.id.ajout) ;
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				WelcomeScreen.this.addSchedule() ;
			}// onClick(View)
		});
	}// initializeAddSchedule()

	/**
	 * Remove the schedule.
	 */
	private void deleteSchedule() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Confirmation de suppression.")
		.setTitle(nameCurrentSchedule);
		builder.setIcon(RESULT_OK);

		//Valider la suppression
		builder.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
			//@Override
			public void onClick(DialogInterface dialog, int which) {
				WelcomeScreen.this.adapter.removeSchedule(nameCurrentSchedule);
				dialog.dismiss();
			}// onClick(View)
		});

		//Annuler la suppression
		builder.setNegativeButton("Non", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}// onClick(View)
		});
		Dialog dialog_return = builder.create();
		dialog_return.show();
	}//deleteSchedule

	/**
	 * Display Schedule details.
	 * (Name, creationDate, lastUpdate, ...)
	 */
	public void detailsDisplay() {
		Schedule s = null ;
		try {
			s = this.db.getScheduleWithName(this.nameCurrentSchedule);
			StringBuilder info = new StringBuilder() ;
			info.append("Nom : ");
			info.append(this.nameCurrentSchedule);
			info.append("\n");
			info.append("Crée le : ");
			info.append(s.getCreated());
			info.append("\n");
			info.append("Dernière mise à jour : ");
			String lm = s.getLastModif() ;
			if (lm.equalsIgnoreCase("null")) {
				lm = "Jamais" ;
			}// if
			info.append(lm);
			info.append("\n");

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(info.toString())
			.setTitle("Informations");
			builder.setIcon(RESULT_OK);
			builder.setNeutralButton("OK", null);
			Dialog dialog_return = builder.create();
			dialog_return.show();
		} catch (AAAException e) {
			// L'edt n'existe pas
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show() ;
		}// try
	}//detailsDisplay

//	/**      * {@inheritDoc}
//	 */
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {            
//		this.getMenuInflater().inflate(R.layout.w_screen_menu, menu);
//		return super.onCreateOptionsMenu(menu);
//	}// onCreateOptionsMenu(Menu)


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.itemAjouter :
			this.addSchedule() ;
			break ;

		case R.id.itemSync :
			this.updateAllSchedules() ;
			break ;

		case R.id.itemOptions :
			this.editOptions() ;
			break ;

		case R.id.itemAide :
			break ;

		case R.id.itemQuitter :
		}
		return false ;
	}// onOptionsItemSelected(MenuItem  
	
	protected void updateAllSchedules() {
//		UpdateManager um = UpdateManager.getInstance() ;
		int nSchedules = this.adapter.getCount() ;
		for(int schedule=0; schedule<nSchedules; ++schedule) {
			this.db.setScheduleStatus(this.adapter.getItem(schedule), STATUS_WAITING_FOR_UPDATE) ;
			Intent intent = new Intent(this, UpdateManager.class) ;
			intent.putExtra("aaa.schedule.name", this.adapter.getItem(schedule)) ;
			Log.d("aaa", "Try to start service -> "+this.adapter.getItem(schedule)) ;
			Log.d("aaa", "Intent -> "+intent) ; 
			this.startService(intent) ;
//			um.addQueue(this.adapter.getItem(schedule)) ;
		}// for
		this.adapter.notifyDataSetChanged() ;
	}

	public void addSchedule () {
		Intent intent = new Intent(WelcomeScreen.this, CreateScheduleScreen.class) ;
		this.startActivity(intent) ;
	}

	public void editOptions () {
		Intent intent = new Intent(WelcomeScreen.this, PreferenceScreen.class) ;
		this.startActivity(intent) ;
	}

//	@Override
//	protected void onDestroy() {
//		super.onDestroy();
//		UpdateManager.getInstance().removeListener(this) ;
//	}

	public void onUpdate (Object... args) {
//		Log.e("aaa", "WS.onUpdate "+args[0]+" => "+args[1]) ;
		if ((args.length >= 3) && (args[2] instanceof AAAException)) {
			AAAException ex = (AAAException) args[2] ;
			Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG) ;
		}// if
		this.adapter.notifyDataSetChanged() ;
//		UpdateManager um = UpdateManager.getInstance() ;
		int nSchedules = this.adapter.getCount() ;
		int schedule=0;
		boolean isUpdating = false ;
		while ((schedule < nSchedules) && !isUpdating) {
			int status = this.db.getScheduleStatus(this.adapter.getItem(schedule)) ;
			isUpdating = (status == STATUS_UPDATING) || (status == STATUS_WAITING_FOR_UPDATE) ;
			++schedule ;
		}// while
		if (!isUpdating) {
			LoaderActionBarItem refreshItem = (LoaderActionBarItem) this.getActionBar().getItem(REFRESH) ;
			refreshItem.setLoading(false) ;
		}// if
	}
	
	@Override
	public void onBackPressed() {
		this.getQuitApplicationDialog() ;
	}
	
	public String getNameCurrentSchedule() {
		return this.nameCurrentSchedule ;
	}
	
	protected void getQuitApplicationDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this) ;
		builder.setMessage("Voulez vous-quittez l'application ?") ;
		builder.setIcon(RESULT_OK) ;

		builder.setPositiveButton("Oui", new QuitApplicationListener(this));

		builder.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss() ;
			}// onClick(View)
		}) ;
		
		builder.create().show() ;
	}// getQuitApplciationDialog()
	
	class QuitApplicationListener implements DialogInterface.OnClickListener {
		protected WelcomeScreen container ;
		
		/**
		 * @param container
		 */
		public QuitApplicationListener(WelcomeScreen container) {
			super();
			this.container = container;
		}

		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss() ;
			this.container.finish() ;
		}// onClick(View)
	}

}
